package com.car.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import com.car.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalException {

    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Result<?> handler(MyException myException) {
        return Result.fail(myException.getCode(), myException.getMessage());
    }

    @ExceptionHandler(NotRoleException.class)
    @ResponseBody
    public Result<?> noRole() {
        return Result.fail(HttpServletResponse.SC_FORBIDDEN, "您非管理员 无权操作");
    }

    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    public Result<?> noLogin() {
        return Result.fail(HttpServletResponse.SC_UNAUTHORIZED, "token无效 请重新登录");
    }


    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<String> handleException(Exception exception, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        return Result.fail(requestURI + "\t请求失败\t" + exception.getMessage());
    }
}
